package fr.hoteia.appengine.archetype.server.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.mail.AuthenticationFailedException;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import org.apache.commons.lang.StringUtils;
import org.apache.velocity.app.VelocityEngine;
import org.springframework.mail.MailException;
import org.springframework.mail.MailSendException;
import org.springframework.ui.velocity.VelocityEngineUtils;

import fr.hoteia.appengine.archetype.client.Constants;
import fr.hoteia.appengine.archetype.server.service.EmailManager;
import fr.hoteia.appengine.archetype.server.web.form.ContactForm;
import fr.hoteia.appengine.archetype.server.web.util.DateUtil;

/**
 * <p>
 * <a href="EmailManagerImpl.java.html"><i>View Source</i></a>
 * </p>
 *
 * @author Denis GOSSET <a href="http://www.hoteia.com"><i>Hoteia.com</i></a>
 * 
 */
public class EmailManagerImpl extends BaseManager implements EmailManager {

    private VelocityEngine velocityEngine;
    
    public void setVelocityEngine(VelocityEngine velocityEngine) {
        this.velocityEngine = velocityEngine;
    }

	public String sendEmailContact(ContactForm contactForm) throws MailSendException, MailException, AuthenticationFailedException,
			Exception {
		String stringToReturn = Constants.EMPTY;

		String languageCode = Constants.LANGUAGE_DEFAULT_CODE;
		String currentDate = DateUtil.formatDate(new Date(), Constants.LANGUAGE_FORMAT_TYPE_SHORT, languageCode);

		if(StringUtils.isEmpty(contactForm.getPhone())){
			contactForm.setPhone("N/A");
		}
		if(StringUtils.isEmpty(contactForm.getFax())){
			contactForm.setFax("N/A");
		}
		if(StringUtils.isEmpty(contactForm.getMobile())){
			contactForm.setMobile("N/A");
		}
		if(StringUtils.isEmpty(contactForm.getWebsite())){
			contactForm.setWebsite("N/A");
		}
		
		Map<String, Object> model = new HashMap<String, Object>();
		model.put("currentDate", currentDate);
		
		contactForm.setMessage(contactForm.getMessage().replace("\n", "<br/>"));
		
		model.put("contactForm", contactForm);

		String namePortal = Constants.APP_NAME.replace(" ", "");
		String subject = "[" + namePortal.toUpperCase() + "][CONTACT]";

		subject = subject + "[" + languageCode.toUpperCase() + "]" + Constants.SPACE + contactForm.getSubject();

		InternetAddress internetAddressFrom = new InternetAddress(Constants.HOTEIA_EMAIL_CONTACT, Constants.HOTEIA_EMAIL_CONTACT_NAME);

		List<InternetAddress> internetAddressTo = new ArrayList<InternetAddress>();
		internetAddressTo.add(new InternetAddress(Constants.HOTEIA_EMAIL_ADMIN, Constants.HOTEIA_EMAIL_ADMIN_NAME));
		internetAddressTo.add(new InternetAddress(Constants.HOTEIA_EMAIL_CONTACT, Constants.HOTEIA_EMAIL_CONTACT_NAME));

		Message message = getMessage(internetAddressFrom, internetAddressTo, subject, model, namePortal, "contact", languageCode );

		Transport.send(message);
		
		return stringToReturn;
	}
	
    
	private Message getMessage(InternetAddress internetAddressFrom, List<InternetAddress> internetAddressTo, String subject, Map<String, Object> model, String namePortal, String nameVelocityTemplate, String codeLanguage) throws MailSendException, MailException, AuthenticationFailedException, Exception {
    	Properties props = new Properties();
        Session session = Session.getDefaultInstance(props, null);

        Message message = new MimeMessage(session);
        message.setFrom(internetAddressFrom);
        for (Iterator<InternetAddress> iterator = internetAddressTo.iterator(); iterator.hasNext();) {
        	InternetAddress internetAddress = (InternetAddress) iterator.next();			
            message.addRecipient(Message.RecipientType.TO, internetAddress);
		}
        message.setSubject(subject);

        MimeMultipart mimeMultipart = new MimeMultipart("alternative");// multipart/mixed or mixed or related or alternative
		message.setContent(mimeMultipart);
		
		String prefixTemplateName = "velocity_" + namePortal + "_" + nameVelocityTemplate + "_" + codeLanguage;
		String htmlTemplateName = prefixTemplateName.toLowerCase() + "_html_content.vm";
		String textTemplateName = prefixTemplateName.toLowerCase() + "_html_content.vm";

		BodyPart textBodyPart = new MimeBodyPart();
		textBodyPart.setContent( VelocityEngineUtils.mergeTemplateIntoString( velocityEngine, htmlTemplateName.toLowerCase(), model) , "text/plain");
		mimeMultipart.addBodyPart(textBodyPart);

		BodyPart htmlBodyPart = new MimeBodyPart();
		htmlBodyPart.setContent(VelocityEngineUtils.mergeTemplateIntoString( velocityEngine, textTemplateName.toLowerCase(), model) , "text/html");
		mimeMultipart.addBodyPart(htmlBodyPart);
        
        return message;
	}
}
